import json

from django.core.serializers import get_serializer
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from rest_framework.generics import RetrieveAPIView, UpdateAPIView, ListAPIView
from rest_framework.response import Response

import datetime
from django.utils import timezone
from houses.models import House
from orders.models import Order
from orders.serializers import OrderSerializer


class OrderHandler(View):
    """订单"""

    def post(self, request):
        """提交订单"""
        data = json.loads(request.body.decode())
        user = request.user
        house_id = data.get("house_id")
        begin_date = data.get("start_date")
        end_date = data.get("end_date")
        # 参数检查
        if not all((house_id, begin_date, end_date)):
            return JsonResponse({"code": 9999, "errmsg": "参数不全"})
        # 查询房屋是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'code': 9999, 'errmsg': '房源不存在'})
        # if not house:
        #     return JsonResponse({'code': 9999, 'errmsg': '房源不存在'})
        # 预订的房屋是否是房东自己的
        if user.id == house.user_id:
            return JsonResponse({"code": 9999, "errmsg": "无法下单"})
        # 判断日期是否可以
        days = (datetime.datetime.strptime(end_date, "%Y-%m-%d") - datetime.datetime.strptime(begin_date,
                                                                                              "%Y-%m-%d")).days + 1
        if days <= 0:
            return JsonResponse({'code': 9999, 'errmsg': '日期不对，无法下单'})
            # 确保用户预订的时间内，房屋没有被别人下单
        # try:
        #     my_order = Order.objects.get(house_id=house_id)
        # except Exception as e:
        #     my_order = None
        # if my_order.begin_date >= end_date or my_order.end_date <= begin_date:
        #     return JsonResponse({'code': 9999, 'errmsg': '房屋已经被下单'})
        # 判断用户预订的时间内，房屋没有被别人下单，看下这段代
        # 判断该时间段房间是否被出租
        orders = house.order_set.all()
        for old_order in orders:
            old_start_date = old_order.begin_date
            old_end_date = old_order.end_date
            if begin_date >= old_end_date or end_date > old_start_date:
                pass
            else:
                return JsonResponse({'errno': 9999, 'errmsg': '租房日期与其他订单冲突'})
        price = house.price
        amount = price * days
        # order_id = "%s%09d" % (timezone.localtime().strftime('%Y%m%d%H%M%S'), user.id)
        Order.objects.create(
            # id=order_id,
            user=user,
            house_id=house_id,
            begin_date=begin_date,
            end_date=end_date,
            days=days,
            house_price=price,
            amount=amount,
            status=Order.ORDER_STATUS['WAIT_ACCEPT']
        )
        res = {
            "data": {"order_id": 1},
            "errno": "0",
            "errmsg": "下单成功"
        }
        return JsonResponse(res)


class OrderStatusView(UpdateAPIView):
    serializer_class = OrderSerializer
    queryset = Order.objects.all()

    def update(self, request, *args, **kwargs):
        """
        {
            "errno": "0",
            "errmsg": "操作成功"
        }
        """
        # 1.接收数据
        order_id = self.kwargs.get("order_id")
        data = request.data
        action = data.get('action')
        reason = data.get('reason')
        order = Order.objects.get(id=order_id)
        user = request.user
        # 2.检验数据
        if not user.is_authenticated:
            return Response({'errno': 4101, 'errmsg': '用户未登录'})
        # 3.处理业务
        if action == 'accept':
            data_dict = {'status': 3}
            serializer = self.get_serializer(instance=order, data=data_dict, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        elif action == 'reject':
            data_dict = {'status': 6, 'comment': reason}
            serializer = self.get_serializer(instance=order, data=data_dict, partial=True)
            serializer.is_valid(raise_exception=True)
            serializer.save()
        # 4.返回响应
        res = {
            "errno": "0",
            "errmsg": "操作成功"
        }
        return Response(res)


class UserOrderViews(ListAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    def list(self, request, *args, **kwargs):
        role = request.query_params.get('role')
        user = request.user
        orders = []
        if role == 'custom':
            order = Order.objects.filter(user_id=user.id)
            serializer = self.get_serializer(order, many=True)
            for order in serializer.data:
                data = {
                    'amount': order.get('amount'),
                    "comment": order.get('comment'),
                    "ctime": order.get('create_time'),
                    "days": order.get('days'),
                    "end_date": order.get('end_date'),
                    "order_id": order.get('id'),
                    "start_date": order.get('begin_date'),
                    "status": Order.ORDER_STATUS_ENUM[order.get('status')],
                    # "img_url": order.get('house').get('index_image_url').url,
                    "img_url": "http://image.ihome.site:8888/" + order.get('house').get('index_image_url'),
                    "title": order.get('house').get('title')
                }
                orders.append(data)
        elif role == 'landlord':
            houses = House.objects.filter(user_id=user.id)
            for house in houses:
                order = Order.objects.filter(house_id=house.id)
                serializer = self.get_serializer(instance=order, many=True)
                for order in serializer.data:
                    data = {
                        'amount': order.get('amount'),
                        "comment": order.get('comment'),
                        "ctime": order.get('create_time'),
                        "days": order.get('days'),
                        "end_date": order.get('end_date'),
                        "order_id": order.get('id'),
                        "start_date": order.get('begin_date'),
                        "status": Order.ORDER_STATUS_ENUM[order.get('status')],
                        # "img_url": order.get('house').get('index_image_url').url,
                        "img_url": "http://image.ihome.site:8888/" + order.get('house').get('index_image_url'),
                        "title": order.get('house').get('title')
                    }
                    orders.append(data)
        res = {
            'data': {'orders': orders},
            'errno': "0",
            'errmsg': "OK"
        }
        return Response(res)


class OrderCommentView(UpdateAPIView):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer

    def update(self, request, *args, **kwargs):
        data = request.data
        order = self.get_object()
        user = request.user
        if not user.is_authenticated():
            return Response({'errno': 4101, 'errmsg': '未登录'})
        serializer = self.get_serializer(instance=order, data=data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({
            "errno": "0",
            "errmsg": "评论成功"
        })
